import { useRef } from 'react';
import { ProTable, ActionType, ProColumns } from '@ant-design/pro-components';
import { Button } from 'antd';
import { fieldComponents } from './data/componentMap';

interface ProListProps<T> {
    columns: ProColumns<T>[];
    request: (params: any) => Promise<{ data: T[]; success: boolean; total?: number }>;
    toolBarRender?: () => React.ReactNode[];
    rowKey?: string; // 可自定义 rowKey，默认为 "id"
    pagination?: boolean | { pageSize?: number }; // 分页配置
}

function getColumns(columns:any) {
    const selectKeys = ['Select'];
    return columns.map((item:any) => {
        const { component, componentProps, renderFormItem } = item;
        const RenderItem:any = fieldComponents[component] || null;
        if (RenderItem && RenderItem.valueType) {
            console.log(RenderItem, 'RenderItem');
            return {
                ...item,
                ...RenderItem,
            };
        }
        const fieldProps = {
            placeholder: selectKeys.includes(component) ? '请选择' : undefined,
            ...componentProps,
        };
        if (RenderItem && !renderFormItem) {
            return {
                ...item,
                renderFormItem() {
                    return <RenderItem {...fieldProps} />;
                },
            };
        }
        return item;
    });
}

const ProList = <T extends Record<string, any>>({ 
    columns,
    request,
    toolBarRender,
    rowKey = 'id',
    pagination = { pageSize: 10 },
}: ProListProps<T>) => {
    const actionRef = useRef<ActionType>();
    
    const tableColumns = getColumns(columns);

    return (
        <ProTable<T>
            columns={tableColumns}
            request={async (params, sorter, filter) => {
                const result = await request({ ...params, sorter, filter });
                return {
                    data: result.data,
                    success: result.success,
                    total: result.total,
                };
            }}
            actionRef={actionRef}
            rowKey={rowKey}
            search={{
                labelWidth: 'auto'
            }}
            toolBarRender={toolBarRender}
            pagination={{ pageSize: 10 }}
            form={{
                syncToUrl: true, // 同步搜索参数到 URL
                initialValues: {}, // 允许自定义初始值
            }}
            columnsState={{
                persistenceKey: 'pro-list-columns',
                persistenceType: 'localStorage',
            }}
        />
    );
};

export default ProList;
